// inject.js - 注入到页面中的脚本，用于更深层次的请求拦截
(function() {
  'use strict';

  // 防止重复注入
  if (window.apiMockInjected) {
    return;
  }
  window.apiMockInjected = true;

  // 存储原始的网络API
  const originalFetch = window.fetch;
  const originalXMLHttpRequest = window.XMLHttpRequest;

  // 拦截规则缓存
  let interceptRules = new Map();

  // 请求日志
  let requestLogs = [];

  // 从chrome.storage获取拦截规则
  function loadRules() {
    // 通过content script与background通信
    document.dispatchEvent(new CustomEvent('getMockRules'));
  }

  // 监听规则更新事件
  document.addEventListener('mockRulesUpdated', (event) => {
    if (event.detail && event.detail.rules) {
      interceptRules = new Map(Object.entries(event.detail.rules));
    }
  });

  // 查找匹配的拦截规则
  function findMatchingRule(url, method) {
    for (const [ruleId, rule] of interceptRules) {
      if (rule.enabled && urlMatches(url, rule.urlPattern)) {
        if (!rule.method || rule.method === method) {
          return rule;
        }
      }
    }
    return null;
  }

  // URL匹配函数
  function urlMatches(url, pattern) {
    try {
      if (pattern.startsWith('/') && pattern.endsWith('/')) {
        const regex = new RegExp(pattern.slice(1, -1));
        return regex.test(url);
      } else {
        return url.includes(pattern);
      }
    } catch (error) {
      return false;
    }
  }

  // 记录请求日志
  function logRequest(url, method, intercepted = false, rule = null) {
    const log = {
      url,
      method,
      intercepted,
      rule: rule ? rule.name : null,
      timestamp: Date.now()
    };
    
    requestLogs.push(log);
    
    // 只保留最近100条日志
    if (requestLogs.length > 100) {
      requestLogs = requestLogs.slice(-100);
    }

    // 发送日志到content script
    document.dispatchEvent(new CustomEvent('apiMockLog', {
      detail: log
    }));
  }

  // 记录完整的请求信息
  function recordRequest(url, method, requestHeaders = {}, requestBody = null, responseHeaders = {}, responseBody = null, status = 200) {
    const record = {
      url,
      method: method.toUpperCase(),
      requestHeaders,
      requestBody,
      responseHeaders,
      responseBody,
      status,
      timestamp: Date.now()
    };

    // 发送请求记录到content script
    document.dispatchEvent(new CustomEvent('apiRequestRecord', {
      detail: record
    }));
  }

  // 创建mock响应
  async function createMockResponse(responseModification, url) {
    // 模拟网络延迟
    if (responseModification.delay && responseModification.delay > 0) {
      await new Promise(resolve => setTimeout(resolve, responseModification.delay));
    }

    const responseBody = typeof responseModification.body === 'string' 
      ? responseModification.body 
      : JSON.stringify(responseModification.body);

    const response = new Response(responseBody, {
      status: responseModification.status || 200,
      statusText: responseModification.statusText || 'OK',
      headers: new Headers(responseModification.headers || {})
    });

    // 添加url属性以保持兼容性
    Object.defineProperty(response, 'url', { 
      value: url,
      writable: false,
      enumerable: true,
      configurable: false
    });

    return response;
  }

  // 拦截fetch请求
  window.fetch = function(...args) {
    const [resource, options = {}] = args;
    const url = resource instanceof Request ? resource.url : resource;
    const method = options.method || (resource instanceof Request ? resource.method : 'GET');

    // 提取请求头和请求体
    const requestHeaders = {};
    if (options.headers) {
      if (options.headers instanceof Headers) {
        for (const [key, value] of options.headers.entries()) {
          requestHeaders[key] = value;
        }
      } else {
        Object.assign(requestHeaders, options.headers);
      }
    }

    let requestBody = null;
    if (options.body) {
      try {
        requestBody = typeof options.body === 'string' ? JSON.parse(options.body) : options.body;
      } catch (error) {
        requestBody = options.body;
      }
    }

    const rule = findMatchingRule(url, method.toUpperCase());

    if (rule) {
      logRequest(url, method, true, rule);

      // 如果有响应修改，返回mock数据
      if (rule.responseModification) {
        const mockResponse = createMockResponse(rule.responseModification, url);
        
        // 记录mock请求
        recordRequest(
          url, 
          method, 
          requestHeaders, 
          requestBody, 
          rule.responseModification.headers || {}, 
          rule.responseModification.body, 
          rule.responseModification.status || 200
        );

        return mockResponse;
      }

      // 如果只有请求修改，修改请求后继续发送
      if (rule.requestModification) {
        const modifiedOptions = { ...options };
        
        if (rule.requestModification.headers) {
          modifiedOptions.headers = {
            ...modifiedOptions.headers,
            ...rule.requestModification.headers
          };
        }

        if (rule.requestModification.body) {
          modifiedOptions.body = typeof rule.requestModification.body === 'string'
            ? rule.requestModification.body
            : JSON.stringify(rule.requestModification.body);
        }

        return originalFetch.call(this, resource, modifiedOptions).then(response => {
          // 记录实际响应
          response.clone().text().then(responseText => {
            try {
              const responseBody = JSON.parse(responseText);
              const responseHeaders = {};
              for (const [key, value] of response.headers.entries()) {
                responseHeaders[key] = value;
              }
              
              recordRequest(url, method, requestHeaders, requestBody, responseHeaders, responseBody, response.status);
            } catch (error) {
              recordRequest(url, method, requestHeaders, requestBody, {}, responseText, response.status);
            }
          }).catch(() => {
            recordRequest(url, method, requestHeaders, requestBody, {}, null, response.status);
          });
          return response;
        });
      }
    }

    // 记录所有请求（包括未拦截的）
    logRequest(url, method, false);
    
    // 发送原始请求并记录响应
    return originalFetch.apply(this, args).then(response => {
      // 记录响应
      response.clone().text().then(responseText => {
        try {
          const responseBody = JSON.parse(responseText);
          const responseHeaders = {};
          for (const [key, value] of response.headers.entries()) {
            responseHeaders[key] = value;
          }
          
          recordRequest(url, method, requestHeaders, requestBody, responseHeaders, responseBody, response.status);
        } catch (error) {
          recordRequest(url, method, requestHeaders, requestBody, {}, responseText, response.status);
        }
      }).catch(() => {
        recordRequest(url, method, requestHeaders, requestBody, {}, null, response.status);
      });
      
      return response;
    }).catch(error => {
      recordRequest(url, method, requestHeaders, requestBody, {}, null, 0);
      throw error;
    });
  };

  // 拦截XMLHttpRequest
  const OriginalXHR = window.XMLHttpRequest;
  window.XMLHttpRequest = function() {
    const xhr = new OriginalXHR();
    const originalOpen = xhr.open;
    const originalSend = xhr.send;
    const originalSetRequestHeader = xhr.setRequestHeader;

    let url, method, requestHeaders = {}, requestData = null;

    xhr.open = function(m, u, ...args) {
      method = m.toUpperCase();
      url = u;
      return originalOpen.call(this, m, u, ...args);
    };

    xhr.setRequestHeader = function(name, value) {
      requestHeaders[name] = value;
      return originalSetRequestHeader.call(this, name, value);
    };

    xhr.send = function(data) {
      requestData = data;
      
      const rule = findMatchingRule(url, method);

      if (rule) {
        logRequest(url, method, true, rule);

        // 如果有响应修改，直接返回mock数据
        if (rule.responseModification) {
          setTimeout(() => {
            try {
              const responseData = typeof rule.responseModification.body === 'string'
                ? rule.responseModification.body
                : JSON.stringify(rule.responseModification.body);

              // 记录mock请求
              recordRequest(
                url, 
                method, 
                requestHeaders, 
                requestData, 
                rule.responseModification.headers || {}, 
                rule.responseModification.body, 
                rule.responseModification.status || 200
              );

              // 设置响应属性
              Object.defineProperty(xhr, 'status', { 
                value: rule.responseModification.status || 200,
                writable: false 
              });
              Object.defineProperty(xhr, 'statusText', { 
                value: rule.responseModification.statusText || 'OK',
                writable: false 
              });
              Object.defineProperty(xhr, 'responseText', { 
                value: responseData,
                writable: false 
              });
              Object.defineProperty(xhr, 'response', { 
                value: responseData,
                writable: false 
              });
              Object.defineProperty(xhr, 'readyState', { 
                value: 4,
                writable: false 
              });

              // 设置响应头
              const responseHeaders = rule.responseModification.headers || {};
              const headerString = Object.entries(responseHeaders)
                .map(([key, value]) => `${key}: ${value}`)
                .join('\r\n');

              xhr.getAllResponseHeaders = function() {
                return headerString;
              };

              xhr.getResponseHeader = function(name) {
                return responseHeaders[name] || null;
              };

              // 触发事件
              if (xhr.onreadystatechange) {
                xhr.onreadystatechange.call(xhr);
              }

              if (xhr.onload) {
                xhr.onload.call(xhr);
              }

              // 触发load事件
              const loadEvent = new Event('load');
              xhr.dispatchEvent(loadEvent);

            } catch (error) {
              if (xhr.onerror) {
                xhr.onerror.call(xhr);
              }
            }
          }, rule.responseModification.delay || 0);

          return;
        }

        // 如果只有请求修改，修改请求后继续发送
        if (rule.requestModification) {
          // 修改请求头
          if (rule.requestModification.headers) {
            Object.entries(rule.requestModification.headers).forEach(([name, value]) => {
              xhr.setRequestHeader(name, value);
            });
          }

          // 修改请求体
          const modifiedData = rule.requestModification.body || data;
          const finalData = typeof modifiedData === 'string' ? modifiedData : JSON.stringify(modifiedData);
          
          // 监听响应完成事件来记录请求
          const originalOnReadyStateChange = xhr.onreadystatechange;
          xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
              // 记录实际请求和响应
              try {
                const responseBody = JSON.parse(xhr.responseText);
                const responseHeaders = {};
                const headerString = xhr.getAllResponseHeaders();
                if (headerString) {
                  headerString.split('\r\n').forEach(line => {
                    const [key, value] = line.split(': ');
                    if (key && value) {
                      responseHeaders[key] = value;
                    }
                  });
                }
                
                recordRequest(url, method, requestHeaders, requestData, responseHeaders, responseBody, xhr.status);
              } catch (error) {
                recordRequest(url, method, requestHeaders, requestData, {}, xhr.responseText, xhr.status);
              }
            }
            
            if (originalOnReadyStateChange) {
              originalOnReadyStateChange.call(this);
            }
          };
          
          return originalSend.call(this, finalData);
        }
      }

      // 记录正常请求
      logRequest(url, method, false);
      
      // 监听响应完成事件来记录请求
      const originalOnReadyStateChange = xhr.onreadystatechange;
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          // 记录实际请求和响应
          try {
            const responseBody = JSON.parse(xhr.responseText);
            const responseHeaders = {};
            const headerString = xhr.getAllResponseHeaders();
            if (headerString) {
              headerString.split('\r\n').forEach(line => {
                const [key, value] = line.split(': ');
                if (key && value) {
                  responseHeaders[key] = value;
                }
              });
            }
            
            recordRequest(url, method, requestHeaders, requestData, responseHeaders, responseBody, xhr.status);
          } catch (error) {
            recordRequest(url, method, requestHeaders, requestData, {}, xhr.responseText, xhr.status);
          }
        }
        
        if (originalOnReadyStateChange) {
          originalOnReadyStateChange.call(this);
        }
      };

      return originalSend.call(this, data);
    };

    return xhr;
  };

  // 保持XMLHttpRequest原型链
  window.XMLHttpRequest.prototype = OriginalXHR.prototype;

  // 初始化时加载规则
  loadRules();

  // 定期重新加载规则（以防规则更新）
  setInterval(loadRules, 5000);

})();